<?php

namespace app\stationpc\controller;

use app\model\StationOrder as ModelStationOrder;
use app\model\StationMemberInfo as ModelStationMemberInfo;
use app\model\UserOrder as ModelUserOrder;
use app\model\CourierOrder as ModelCourierOrder;
use app\model\CourierInfo as ModelCourierInfo;
use app\model\StationOrderLog as ModelStationOrderLog;


class Express extends Member
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 快件管理列表 \n
     * URI : /stationpc/express.order.list
     * @param :
     *  name     | type   | null| description
     * ----------|--------|-----|-------------
     *  page     | int    | 必填 | 页码
     *  listRows | int    | 必填 | 一页的条数
     *
     *  orderNumber       | int    | 选填 | 订单编号
     *  state             | int    | 选填 | 类型 60：派件；65：中转; 40:揽收;55:拆箱 100:异常
     *  type              | int    | 选填 | 列表类型   1出库订单 2入库订单
     *  memberInfoName    | string | 选填 | 操作人
     *  order             | string | 选填 | 排序 添加时间（‘desc’）
     *
     *  @return :
     *  name        | type   | description
     * -------------|--------|-------------
     *  totalPages  | string | 总页数
     *
     *  stationOrderId | int | 站点订单ID
     *  orderNumber | string | 订单编号
     *  state       | int    | 出库类型 60：派件；65：中转; 40:揽收;55:拆箱 100:异常
     *  memberName  | string | 操作人员
     *
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function expressOrderList(){
        $int_now_page = $this->_getContentParams('page'); // 当前页码
        _toValidate('id', $int_now_page, 10005);
        $int_list_rows = $this->_getContentParams('listRows'); // 一页的条数
        _toValidate('id', $int_list_rows, 10006);
        $int_type = $this->_getContentParams('type');     //列表类型   1出库订单 2入库订单
        _toCompare(in_array($int_type, [1, 2]), '===', false, 30006);
        $str_order_number = $this->_getContentParams('orderNumber');     //订单编号
        $int_state = $this->_getContentParams('state');     //类型 60：派件；65：中转; 40:揽收;55:拆箱 100:异常
        $str_member_name = $this->_getContentParams('memberInfoName');     //操作人
        $str_order = $this->_getContentParams('order');     //排序

        $arr_where = $this->expressOrderListWhere($int_type, $str_order_number, $int_state, $str_member_name);
        $str_order = $this->listOrder('gmt_create', $str_order);

        $int_total_rows = ModelStationOrder::getInstance()->toCount($arr_where);
        $int_total_pages = (int)ceil($int_total_rows / $int_list_rows);//总页数
        _toCompare(($int_now_page > $int_total_pages && $int_total_pages > 0), '===', true, 10007);
        $int_first_row = $int_list_rows * ($int_now_page - 1);//从第几条开始查询
        $str_field = 'id AS stationOrderId,order_number AS orderNumber,state,operator_id AS operatorId,is_unusual AS isUnusual';
        $arr_list = ModelStationOrder::getInstance()->toSelect($arr_where, $str_field, $int_first_row, $int_list_rows, $str_order);
        $arr_list = $this->expressOrderListModify($arr_list);
        _returnData(['totalPages' => $int_total_pages, 'list' => $arr_list]);
    }

    /**
     * 快件管理列表 -> 筛选
     * @param $int_type
     * @param $str_order_number
     * @param $int_state
     * @param $str_member_name
     * @return array
     */
    private function expressOrderListWhere($int_type, $str_order_number, $int_state, $str_member_name){
        $arr_where = [];
        if($int_type == 1){
            $arr_where['state']= ['in', '65,60'];
        }else if ($int_type == 2){
            $arr_where['state']= ['in', '40,55'];
        }

        if($str_order_number != ''){
            $arr_where['order_number'] = ['like', "%$str_order_number%"];
        }
        if($str_member_name != ''){
            $arr_info_id = ModelStationMemberInfo::getInstance()->toColumn(['member_name' => ['like', "%$str_member_name%"]], 'id');
            $arr_where['operator_id'] = ['in', implode(",", $arr_info_id)];
        }
        if($int_state != ''){
            if($int_state == 100){
                $arr_where['is_unusual'] = 1;
            }else{
                $arr_where['state'] = $int_state;
            }
        }
        return $arr_where;
    }

    /**
     * 快件管理列表 -> 操作人名称
     * @param $arr_list
     * @return mixed
     */
    private function expressOrderListModify($arr_list){
        foreach ($arr_list as &$value) {
            $value['memberName'] = ModelStationMemberInfo::getInstance()->toValue(['id' => $value['operatorId']], 'member_name');
            $value['memberName'] = $value['memberName']?$value['memberName']:'';
            if ($value['isUnusual'] == 1){
                $value['state'] = 100;
            }
        }
        return $arr_list;
    }

    /**
     * 快件管理列表->删除 \n
     * URI : /stationpc/express.order.list.del
     * @param :
     *  name     | type   | null| description
     * ----------|--------|-----|-------------
     * stationOrderId     | int | 订单ID
     *
     *  @return :
     *  name        | type   | description
     * -------------|--------|-------------
     *
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function expressOrderListDelete(){
        $int_station_order_id = $this->_getContentParams('stationOrderId'); // 订单ID
        _toValidate('id', $int_station_order_id, 10009);
        ModelStationOrder::getInstance()->toDelete(['id' => $int_station_order_id]);
        _returnData();
    }

    /**
     * 快件管理列表->查看 \n
     * URI : /stationpc/express.order.list.details
     * @param :
     *  name     | type   | null| description
     * ----------|--------|-----|-------------
     *  stationOrderId    | int | 必填 | 站点订单ID
     *  orderNumber       | int | 选填 | 收入明细（查看时必填）
     *
     * @return :
     *  name            | type   | description
     * -----------------|--------|-------------
     *  orderId         | int    | 订单ID
     *  orderSn         | string | 订单编号
     *  expressOrderSn  | float  | 快递公司运单号
     *  gmtcCreate      | string | 下单时间
     *  doorTime        | string | 期望上门时间 arrayX2
     *  orderState      | string | 状态信息
     *  state           | int    | 状态：25：未支付，已取件：
     *  protectPrice    | string | 物品保价
     *  itemType        | string | 物品类型
     *  itemWeight      | int    | 物品重量
     *  pickCode        | string | 取件码
     *  courierRealName | string | 快递员姓名
     *  courierMobile   | string | 快递员电话
     *  courierType     | string | 所属快递 'free:自由快递；profession:官方快递'
     *  package         | string | 包装
     *
     *  寄件人信息 senderInfo  array
     *  name            | string | 姓名
     *  phone           | string | 电话
     *  provName        | string | 省
     *  cityName        | string | 市
     *  countyName      | string | 区
     *  streetName      | string | 街道
     *  address         | string | 详细地址
     *
     *  收件人 recipientInfo  array
     *  name            | string | 姓名
     *  phone           | string | 电话
     *  provName        | string | 省
     *  cityName        | string | 市
     *  countyName      | string | 区
     *  streetName      | string | 街道
     *  address         | string | 详细地址
     *
     *  操作信息列表 list array
     *  orderLogId      | int    | 订单记录ID
     *  operator        | string | 操作者
     *  operatorMobile  | string | 操作者账号
     *  cityName        | string | 账号
     *  gmtCreate       | string | 操作时间
     *  state           | int    | 订单状态:'40：已入库；50封箱；55:拆箱；60：出库；65：中转',
     *  remark          | string | 备注
     *
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function expressOrderListDetails()
    {
        $int_station_order_id = $this->_getContentParams('stationOrderId'); // 站点订单ID
        $str_order_number = $this->_getContentParams('orderNumber'); // 订单编号

        if($str_order_number != ''){
            $int_order_id = ModelStationOrder::getInstance()->toValue(['order_number' => $str_order_number], 'order_id'); //订单ID
        }else{
            _toValidate('id', $int_station_order_id, 10009);
            $int_order_id = ModelStationOrder::getInstance()->toValue(['id' => $int_station_order_id], 'order_id'); //订单ID
        }
        $arr_data = ModelUserOrder::getInstance()->toFind(['order_id' => $int_order_id], 'order_id AS orderId,order_sn AS orderSn,express_order_sn AS expressOrderSn,gmt_create AS gmtcCreate,door_time AS doorTime,order_state AS orderState,protect_price AS protectPrice,item_type AS itemType,item_weight AS itemWeight,sender_info AS senderInfo,recipient_info AS recipientInfo,pick_code AS pickCode,package');
        $arr_list = (array)ModelstationOrderLog::getInstance()->toSelect(['order_id' => $int_station_order_id], 'id AS orderLogId,member_id AS memberId,gmt_create AS gmtCreate,state,remark');

        $arr_list = $this->expressOrderListDetailsListModify($arr_list);
        $arr_data = $this->expressOrderListDetailsDataModify($arr_data);

        _returnData(['data' => $arr_data, 'list' => $arr_list]);
    }

    /**
     * @param $arr_list
     * @return mixed
     */
    private function expressOrderListDetailsListModify($arr_list){
        foreach ($arr_list as &$value){
            $value['operator'] = (string)ModelStationMemberInfo::getInstance()->toValue(['id' => $value['memberId']], 'member_name');
            $value['operatorMobile'] = (string)ModelStationMemberInfo::getInstance()->toValue(['id' => $value['memberId']], 'mobile');
        }
        return $arr_list;
    }

    /**
     * @param $arr_data
     * @return mixed
     */
    private function expressOrderListDetailsDataModify($arr_data){
        $arr_data['doorTime'] = explode("|", $arr_data['doorTime']);
        $arr_data['doorTime'][0] = date("Y-m-d H:i:s", $arr_data['doorTime'][0]);
        $arr_data['doorTime'][1] = date("Y-m-d H:i:s", $arr_data['doorTime'][1]);
        $arr_data['senderInfo'] = json_decode($arr_data['senderInfo']);
        $arr_data['recipientInfo'] = json_decode($arr_data['recipientInfo']);
        $int_courier_id = ModelCourierOrder::getInstance()->toValue(['order_id' => $arr_data['orderId']], 'courier_id');
        $arr_courier_info = ModelCourierInfo::getInstance()->toFind(['id' => $int_courier_id], 'real_name AS realName,mobile,type');
        $arr_data['courierRealName'] = (string)$arr_courier_info['realName'];
        $arr_data['courierMobile'] = (string)$arr_courier_info['mobile'];
        $arr_data['courierType'] = (string)$arr_courier_info['type'];
        return $arr_data;
    }

    /**
     * 快件管理列表-查看-新增备注 \n
     * URI : /stationpc/add.remark
     * @param :
     *  name         | type   | null | description
     * --------------|--------|------|-------------
     *  stationOrderId | int  | 必填 | 站点订单ID
     *  remark       | string | 必填 | 备注
     *  isPick       | int    | 必填 |  收发站点  0:其他  1：发件站点 2:收件站点
     *
     * @return
     *  name    | type | description
     * ---------|------|-------------
     *  ------- | ---- | 无
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addRemark(){
        $int_station_order_id = $this->_getContentParams('stationOrderId'); // 站点订单ID
        _toValidate('id', $int_station_order_id, 10009);
        $str_remark = $this->_getContentParams('remark'); // 备注
        _toCompare(empty($str_remark), '===', true, 30007);
        $int_is_pick = $this->_getContentParams('isPick'); //
        _toCompare(in_array($int_is_pick, [0, 1, 2]), '===', false, 30008);
        ModelStationOrderLog::getInstance()->stationOrderLogAdd($this->station_id, $this->station_id, $int_station_order_id, $int_is_pick,2, $str_remark);
        _returnData();
    }

}
